Plotly for dynamic visualization. There are two main ways you can use plotly.
You can use plotly.express as px, which is much simplified version of creating plots. One line of code will produce a nice graph.
You can use plotly.graph_objs as go, which is more flexible and provides more control and customization options.
For beginners, Plotly Express is often the better choice.
In this tutorial, I will show you how to use Plotly, but for more information check here. For full API, see here.
import numpy as np
import pandas as pd
plotly.express¶import plotly.express as px
fig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])
fig.show()
fruits = ["apples", "oranges", "bananas"]
fig = px.line(x=fruits, y=[1,3,2], color=px.Constant("This year"),
labels=dict(x="Fruit", y="Amount", color="Time Period"))
fig.add_bar(x=fruits, y=[2,1,3], name="Last year")
fig.show()
#load the data
df = px.data.iris()
df.head()
| sepal_length | sepal_width | petal_length | petal_width | species | species_id | |
|---|---|---|---|---|---|---|
| 0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa | 1 |
| 1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa | 1 |
| 2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa | 1 |
| 3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa | 1 |
| 4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa | 1 |
# just one line of code
fig = px.scatter(df, x="sepal_width", y="sepal_length")
fig.show()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
labels={
"sepal_width": "Sepal Width (cm)",
"sepal_length": "Sepal Length (cm)",
"species": "Species"
},
title="Iris Sepal Dimensions")
fig.show()
fig.update_layout(
title="Iris Sepal Dimensions",
xaxis_title="Sepal Width (cm)",
yaxis_title="Sepal Length (cm)",
legend_title="Species",
font=dict(
family="Courier New, monospace",
size=18,
color="RebeccaPurple"
)
)
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", symbol="species")
fig.show()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
fig.update_traces(
marker=dict(size=8, symbol="diamond", line=dict(width=2, color="DarkSlateGrey")),
selector=dict(mode="markers"),
)
fig.show()
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="smoker", facet_col="sex", facet_row="time")
fig.show()
df = px.data.gapminder()
df.head()
| country | continent | year | lifeExp | pop | gdpPercap | iso_alpha | iso_num | |
|---|---|---|---|---|---|---|---|---|
| 0 | Afghanistan | Asia | 1952 | 28.801 | 8425333 | 779.445314 | AFG | 4 |
| 1 | Afghanistan | Asia | 1957 | 30.332 | 9240934 | 820.853030 | AFG | 4 |
| 2 | Afghanistan | Asia | 1962 | 31.997 | 10267083 | 853.100710 | AFG | 4 |
| 3 | Afghanistan | Asia | 1967 | 34.020 | 11537966 | 836.197138 | AFG | 4 |
| 4 | Afghanistan | Asia | 1972 | 36.088 | 13079460 | 739.981106 | AFG | 4 |
df = px.data.gapminder().query("country=='United States'")
df.head()
#secon way
# df[df['country']=="United States"]
| country | continent | year | lifeExp | pop | gdpPercap | iso_alpha | iso_num | |
|---|---|---|---|---|---|---|---|---|
| 1608 | United States | Americas | 1952 | 68.44 | 157553000 | 13990.48208 | USA | 840 |
| 1609 | United States | Americas | 1957 | 69.49 | 171984000 | 14847.12712 | USA | 840 |
| 1610 | United States | Americas | 1962 | 70.21 | 186538000 | 16173.14586 | USA | 840 |
| 1611 | United States | Americas | 1967 | 70.76 | 198712000 | 19530.36557 | USA | 840 |
| 1612 | United States | Americas | 1972 | 71.34 | 209896000 | 21806.03594 | USA | 840 |
fig = px.line(df, x="year", y="lifeExp", title='Life Expectancy in United States', markers=True)
fig.show()
# create bar charts
fig = px.bar(df, x='year', y='pop', height=400)
fig.show()
# Themes:
# 'ggplot2', 'seaborn', 'simple_white', 'plotly',
# 'plotly_white', 'plotly_dark', 'presentation',
# 'xgridoff', 'ygridoff', 'gridon', 'none'
# seaborn
fig = px.bar(df, x='year', y='pop', color='lifeExp', labels={'pop': 'Population of Canada'},
height=400, template='seaborn')
fig.show()
# filter 2007 data only from dataset
df = px.data.gapminder()
gapminder2007 = df.query('year == 2007')
# create scatter plot
fig = px.scatter(gapminder2007, x='gdpPercap', y='lifeExp')
fig.show()
# color by continent
fig = px.scatter(gapminder2007, x='gdpPercap', y='lifeExp', color='continent')
fig.show()
# a bubble chart
fig = px.scatter(gapminder2007, x='gdpPercap', y='lifeExp', color='continent', size='pop', size_max=60)
fig.show()
# let's add animation
df = px.data.gapminder()
fig = px.scatter(df, x='gdpPercap', y='lifeExp', color='continent', size='pop', size_max=60,
hover_name='country', log_x=True, animation_frame='year',
animation_group='country', range_x=[25, 10000], range_y=[20,90])
fig.show()
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=[0, 1, 2, 3, 4, 5],
y=[1.5, 1, 1.3, 0.7, 0.8, 0.9]
))
fig.add_trace(
go.Bar(
x=[0, 1, 2, 3, 4, 5],
y=[1, 0.5, 0.7, -1.2, 0.3, 0.4]
))
fig.show()
from plotly.subplots import make_subplots
# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])
# Add traces
fig.add_trace(
go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis data"),
secondary_y=False,
)
fig.add_trace(
go.Scatter(x=[2, 3, 4], y=[4, 5, 6], name="yaxis2 data"),
secondary_y=True,
)
# Add figure title
fig.update_layout(
title_text="Double Y Axis Example"
)
# Set x-axis title
fig.update_xaxes(title_text="xaxis title")
# Set y-axes titles
fig.update_yaxes(title_text="<b>primary</b> yaxis title", secondary_y=False)
fig.update_yaxes(title_text="<b>secondary</b> yaxis title", secondary_y=True)
fig.show()
# Initialize figure with subplots
fig = make_subplots(
rows=2, cols=2, subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4")
)
# Add traces
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1)
fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]), row=1, col=2)
fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]), row=2, col=1)
fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]), row=2, col=2)
# Update xaxis properties
fig.update_xaxes(title_text="xaxis 1 title", row=1, col=1)
fig.update_xaxes(title_text="xaxis 2 title", range=[10, 50], row=1, col=2)
fig.update_xaxes(title_text="xaxis 3 title", showgrid=False, row=2, col=1)
fig.update_xaxes(title_text="xaxis 4 title", type="log", row=2, col=2)
# Update yaxis properties
fig.update_yaxes(title_text="yaxis 1 title", row=1, col=1)
fig.update_yaxes(title_text="yaxis 2 title", range=[40, 80], row=1, col=2)
fig.update_yaxes(title_text="yaxis 3 title", showgrid=False, row=2, col=1)
fig.update_yaxes(title_text="yaxis 4 title", row=2, col=2)
# Update title and height
fig.update_layout(title_text="Customizing Subplot Axes", height=700)
fig.show()
x = np.random.uniform(low=3, high=6, size=(500,))
y = np.random.uniform(low=3, high=4.5, size=(500,))
x2 = np.random.uniform(low=3, high=6, size=(500,))
y2 = np.random.uniform(low=4.5, high=6, size=(500,))
# Build figure
fig = go.Figure()
# Add first scatter trace with medium sized markers
fig.add_trace(
go.Scatter(
mode='markers',
x=x,
y=y,
opacity=0.5,
marker=dict(
color='LightSkyBlue',
size=20,
line=dict(
color='MediumPurple',
width=2
)
),
name='Opacity 0.5'
)
)
# Add second scatter trace with medium sized markers
# and opacity 1.0
fig.add_trace(
go.Scatter(
mode='markers',
x=x2,
y=y2,
marker=dict(
color='LightSkyBlue',
size=20,
line=dict(
color='MediumPurple',
width=2
)
),
name='Opacity 1.0'
)
)
# Add trace with large markers
fig.add_trace(
go.Scatter(
mode='markers',
x=[2, 2],
y=[4.25, 4.75],
opacity=0.5,
marker=dict(
color='LightSkyBlue',
size=80,
line=dict(
color='MediumPurple',
width=8
)
),
showlegend=False
)
)
fig.show()
N = 100
random_x = np.linspace(0, 1, N)
random_y0 = np.random.randn(N) + 5
random_y1 = np.random.randn(N)
random_y2 = np.random.randn(N) - 5
fig = go.Figure()
# Add traces
fig.add_trace(go.Scatter(x=random_x, y=random_y0,
mode='markers',
name='markers'))
fig.add_trace(go.Scatter(x=random_x, y=random_y1,
mode='lines+markers',
name='lines+markers'))
fig.add_trace(go.Scatter(x=random_x, y=random_y2,
mode='lines',
name='lines'))
fig.show()
fig = make_subplots(
rows=2, cols=2,
specs=[[{"type": "xy"}, {"type": "polar"}],
[{"type": "domain"}, {"type": "scene"}]],
)
fig.add_trace(go.Bar(y=[2, 3, 1]),
row=1, col=1)
fig.add_trace(go.Barpolar(theta=[0, 45, 90], r=[2, 3, 1]),
row=1, col=2)
fig.add_trace(go.Pie(values=[2, 3, 1]),
row=2, col=1)
fig.add_trace(go.Scatter3d(x=[2, 3, 1], y=[0, 0, 0],
z=[0.5, 1, 2], mode="lines"),
row=2, col=2)
fig.update_layout(height=700, showlegend=False)
fig.show()
N = 70
fig = go.Figure(data=[go.Mesh3d(x=(70*np.random.randn(N)),
y=(55*np.random.randn(N)),
z=(40*np.random.randn(N)),
opacity=0.5,
color='rgba(244,22,100,0.6)'
)])
fig.update_layout(
scene = dict(
xaxis = dict(nticks=4, range=[-100,100],),
yaxis = dict(nticks=4, range=[-50,100],),
zaxis = dict(nticks=4, range=[-100,100],),),
width=700,
margin=dict(r=20, l=10, b=10, t=10))
fig.show()